//
//  MeViewController.m
//  TravelDiary
//
//  Created by lanou3g on 15/11/11.
//  Copyright © 2015年 YDB MAC. All rights reserved.
//

#import "MeViewController.h"
#import "LoginViewController.h"
#import "XHPathCover.h"
#import "MeTableViewCell.h"
#import <AVOSCloud.h>
#import "CollectViewController.h"
#import "UMSocial.h"


@interface MeViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>

@property(nonatomic,strong)UITableView * tableView ;

@property(nonatomic,strong)NSMutableArray * array ;

@property (nonatomic, strong) XHPathCover *pathCover;

/**注册登录按钮*/
@property (nonatomic, strong) NSString *str;
/** NSUserDefaults 中的isLogin值 */
@property (nonatomic, strong) NSString *string;

//声明一个全局的UIBarButtonItem
@property (nonatomic, strong) UIBarButtonItem *item1;

@property (nonatomic, copy) NSString *myName;

@property (nonatomic, strong) NSDictionary *loginDict;



@property (nonatomic, strong) UIButton *setButton;

@end


@implementation MeViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
  
    //每次加载页面时都要判断用户是否登录
    AVUser * currentUser = [AVUser currentUser];
    if (currentUser == nil) {
        _str = @"登录";
    }else if(currentUser != nil){
        _str = @"注销";
        [_pathCover setInfo:[NSDictionary dictionaryWithObjectsAndKeys:currentUser.username, XHUserNameKey, @"＊＊＊＊＊＊＊", XHBirthdayKey, nil]];
    }

    //左上角按钮
    _item1 = [[UIBarButtonItem alloc]initWithTitle:_str style:UIBarButtonItemStylePlain target:self action:@selector(loginClick:)];
    self.navigationItem.rightBarButtonItems = @[_item1];
}


#pragma mark -- 登录注册事件
- (void)loginClick:(UIBarButtonItem *)bar{
    
    //判断右上角按钮是注销还是登录  如果是登录：点击后进入登录页面  如果是注销点击后注销用户将改为登录
    if ([_str isEqualToString:@"登录"]){
        //跳转到登录页面
        LoginViewController *loVC = [[LoginViewController alloc ] init];
        loVC.myBlock = ^(NSString *name){
            _myName = name;
            [_pathCover setInfo:[NSDictionary dictionaryWithObjectsAndKeys:[AVUser currentUser].username, XHUserNameKey, @"＊＊＊＊＊＊＊", XHBirthdayKey, nil]];
        };
        [self.navigationController pushViewController:loVC animated:YES];
    }else if([_str isEqualToString:@"注销"])
    {
        [_pathCover setInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"请登录", XHUserNameKey, @"＊＊＊＊＊＊＊", XHBirthdayKey, nil]];
        _str = @"登录";
        [_item1 setTitle:_str];
        
        //退出登录,注销用户
        [AVUser logOut];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    //判断用户是否登录
    AVUser * currentUser = [AVUser currentUser];
    if (currentUser != nil) {
        _myName = currentUser.username;
    }
    //TableView的创建
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:(UITableViewStylePlain)];
    self.tableView.dataSource =self ;
    self.tableView.delegate = self ;
    self.tableView.tableFooterView = [[UIView alloc]init];
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"MeTableViewCell" bundle:nil] forCellReuseIdentifier:@"MeTableViewCell"];
    
    
    self.array = [NSMutableArray arrayWithObjects:@"收藏",@"清除缓存",@"夜间模式",@"免责声明", nil];
    [self.view addSubview:self.tableView];
    _pathCover = [[XHPathCover alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), self.view.frame.size.height/3)];
    [_pathCover setBackgroundImage:[UIImage imageNamed:@"MenuBackground"]];
    
    //头像添加
    [_pathCover setAvatarImage:[UIImage imageNamed:@"meicon.png"]];
    [_pathCover.avatarButton addTarget:self action:@selector(avatarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    //判断是否登录
    if ([AVUser currentUser] !=nil) {
        [_pathCover setInfo:[NSDictionary dictionaryWithObjectsAndKeys:[AVUser currentUser].username, XHUserNameKey, @"＊＊＊＊＊＊＊", XHBirthdayKey, nil]];
    }else{
        [_pathCover setInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"请登录", XHUserNameKey, @"＊＊＊＊＊＊＊", XHBirthdayKey, nil]];
    }
    
    
    
    self.tableView.tableHeaderView = self.pathCover;
    __weak MeViewController *wself = self;
    [_pathCover setHandleRefreshEvent:^{
        [wself _refreshing];
    }];
    
    
}
#pragma mark -添加头像
- (void)avatarButtonClick:(UIButton *)sender{
    
    AVUser * currentUser = [AVUser currentUser];
    if (currentUser == nil) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录!" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
        
        
        
    }else if(currentUser != nil){
       
        UIActionSheet *action = [[ UIActionSheet alloc]initWithTitle:@"选取照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册", nil];
        //    [action showInView:self.view];
        [action showFromRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) inView:self.view animated:YES];
        NSLog(@"添加头像");
    }
    
    
    
}
- (void)setImagePickerController:(UIImagePickerControllerSourceType)source{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
    imagePicker.delegate = self;
    
    imagePicker.sourceType = source;
    //对图片进行大小位置选取
    [imagePicker setEditing:YES];
    imagePicker.allowsEditing = YES;
    
    
    //模态推出视图
    [self presentViewController:imagePicker animated:YES completion:nil];
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            [self setImagePickerController:UIImagePickerControllerSourceTypeCamera];
            break;
        case 1:
            [self setImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
            break;
        default:
            break;
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    // UIImageJPEGRepresentation 把图片转化成JPEG的格式，第二个参数填的是一个压缩的系数，一般是 0.5//
    UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    
    //UIImagePNGRepresentation   把图片转换成PNG的格式，不压缩 比较大
    //UIImageJPEGRepresentation  把图片转换成JPEG的格式，第二个参数填的是一个压缩的系数，一般是0.5
//    _data = UIImageJPEGRepresentation(image, 0.5);
    
    
    [_pathCover.avatarButton setImage:image forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:nil];
}





- (void)_refreshing {
    // refresh your data sources
    
    __weak MeViewController *wself = self;
    double delayInSeconds = 4.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [wself.pathCover stopRefresh];
    });
}
#pragma mark- scroll delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [_pathCover scrollViewDidScroll:scrollView];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [_pathCover scrollViewDidEndDecelerating:scrollView];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [_pathCover scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [_pathCover scrollViewWillBeginDragging:scrollView];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1 ;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _array.count ;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MeTableViewCell";
    
    MeTableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    cell.selectedBackgroundView = [[UIView alloc]init];
    cell.titleLabel.text = _array[indexPath.row];
    cell.titleImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"me%ld",(long)indexPath.row]];
    if (indexPath.row == 2) {
        cell.switchMe.hidden = NO;
        cell.jiantou.hidden = YES;
        
    }
    return cell ;
}

#pragma mark--cell的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    switch (indexPath.row) {
        case 0:{
            AVUser *currentUser= [AVUser currentUser];
            if (currentUser ==nil) {
                //未登录,提示用户登录
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先进行登录" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                }];
                [alert addAction:action];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
               //已登录
                CollectViewController *collect = [[CollectViewController alloc]init];
                [self.navigationController pushViewController:collect animated:YES];
            }
            
            
        }
            break;
        case 1:{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"成功" message:@"清除成功" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                }];
                [alert addAction:action];
                [self presentViewController:alert animated:YES completion:nil];
           
        }
            break;
        case 3:{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"声明" message:@"此版本已是最新版本,您可安全使用!" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
            
        }
            break;
        default:
            break;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
